package com.mhc.haval.service.impl;

import com.mhc.haval.constant.MsgCodeEnum;
import com.mhc.haval.dal.model.FuncDO;
import com.mhc.haval.dal.query.FuncQuery;
import com.mhc.haval.exception.HavalCommonException;
import com.mhc.haval.manager.FuncManager;
import com.mhc.haval.service.FuncService;
import com.mhc.haval.vo.FuncVO;
import com.subaru.common.util.BeanCopierUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author Churry
 * @create 2017-08-23 16:23
 **/
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class FuncServiceImpl implements FuncService {

    @Autowired
    private FuncManager funcManager;

    /**
     * 获取所有的功能（权限）列表
     *
     * @return
     */
    @Override
    public List<FuncDO> getFuncList(Map queryMap) throws HavalCommonException {
        try {
            return funcManager.queryFuncListByCondition(queryMap);
        } catch (Exception e) {
            log.error("获取所有的功能（权限）列表失败", e);
            throw new HavalCommonException(MsgCodeEnum.QUERY_FAIL);
        }
    }

    /**
     * 计算总数目
     * @param funcQuery
     * @return
     */
    @Override
    public Integer countByQuery(FuncQuery funcQuery) {
        return funcManager.countByQuery(funcQuery);
    }

    /**
     * 计算总数目
     * @param queryMap
     * @return
     */
    @Override
    public Integer countByQueryMap(Map queryMap) {
        return funcManager.countByQueryMap(queryMap);
    }

    /**
     * 新增/修改权限详情
     *
     * @param funcVO
     * @return
     * @throws HavalCommonException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addOrUpdateFunc(FuncVO funcVO) throws HavalCommonException {
        Optional<FuncVO> funcOptional = Optional.ofNullable(funcVO);
        if (funcOptional.isPresent()) {
            FuncDO funcDO = BeanCopierUtil.convert(funcVO, FuncDO.class);
            //id为空表示新增一条权限
            Optional<Long> funcIdOptional = Optional.ofNullable(funcDO.getFuncId());
            if (funcIdOptional.isPresent()) {
                try {
                    funcManager.updateByPrimaryKeySelective(funcDO);
                } catch (Exception e) {
                    log.error("修改权限详情失败", e);
                    throw new HavalCommonException(MsgCodeEnum.UPDATE_FAIL);
                }
            } else {
                try {
                    funcManager.insertSelective(funcDO);
                } catch (Exception e) {
                    log.error("新增权限详情失败", e);
                    throw new HavalCommonException(MsgCodeEnum.INSERT_FAIL);
                }
            }
            return true;
        } else {
            throw new HavalCommonException(MsgCodeEnum.FUNC_ISNULL);
        }
    }
}
